<?php
/**
 *  经销商商品
 */

namespace app\api\service;

use app\admin\service\LogisticsRules;
use app\api\exception\ThrowException;
use app\api\model\Customer;
use app\api\model\Images;
use app\api\model\OrderItem;
use app\api\model\Product as ProductModel;
use app\api\model\RegionCountry;
use app\api\model\Warehouse;
use app\api\service\Logistics as ServiceLogistics;
use app\api\service\OrderPayment as ServiceOrderPayment;
use app\api\model\OrderPayment as ModelOrderPayment;
use app\api\model\WholesalOrder;
use app\api\model\WholesalOrderItem;
use app\common\Calculate;
use app\common\Common;
use app\facade\Basic;
use app\api\model\Order as ModelOrder;
use think\facade\Config;
use app\api\model\Address as AddressModel;
use think\facade\Db;
use think\facade\Lang;

class DistributorOrder
{
    /**
     *  供应商列表
     */

    public function list($param)
    {

        $where[] = ['is_del', '=', 0];
        $where[] = ['user_id', '=', $param['user_id']];
        $where[] = ['order_category', '=', 'wholesal'];

        if (!empty($param['search_value'])) {
            $where[] = ['order_no', '=', trim($param['search_value'])];
        }

        switch ($param['status']) {
            case '10': // 待支付
                $where[] = ['status', 'in', [10, 21]];
                break;
            case '20': // 审核中
                $where[] = ['status', '=', '20'];
                break;
            case '70': // 已取消
                $where[] = ['status', '=', '70'];
                break;
            case '100': // 已完成
                $where[] = ['status', '=', '100'];
                break;
            default:
        }


        $WholesalOrderModel = new WholesalOrder();


        $result = WholesalOrder::with([
            'item' => function ($query) {
                $query->with([
                    'product' => function ($query) {
                        return $query->with([
                            'brand' => function ($query) {
                                return $query->field('id,name,image');
                            },
                            'category' => function ($query) {
                                return $query->field('id,name');
                            },

                        ])->field('id,cname,category,brand,condition,expiration_date,hashrate,computing_unit,power,main_photo,photo,type,describe,estimated_ship_date,weight');
                    },
                ])->where('is_del', '=', 0)->field('id,order_id,product_id,warehouse_id,original_price,actual_price,is_futures,quantity,lock_qty,arrival_date');
            }
        ])->where($where)
            ->field('id,order_no,user_id,order_num,advance_amount,advance_pay_time,payment_method,status,order_remark,tax_package,tax_package_id,tax_fee,pay_terms,total_amount,pay_amount,pay_status,product_total_amount,product_total_original_amount,create_time')
            ->order('id DESC')
            ->paginate($param['listRows']);
        $order = $result->toArray();
        $photoidsArr = [];
        $photoList = [];
        foreach ($order['data'] as $datum){
            if($datum['item']){
                foreach ($datum['item'] as $productData){
                    if(!empty($productData['product']['main_photo']) ){
                        $photoidsArr[]=$productData['product']['main_photo'];
                    }
                    if ($productData['product']['type'] == 2 && !empty($productData['product']['photo'])) {
                        $photoidsArr[] = explode(',', $productData['product']['photo'])[0];
                    }
                }
            }
        }

        $imageModel = new Images();
        if($photoidsArr){
            $photoList = $imageModel->getImagesByIds($photoidsArr);

            // 将数组转换为以ID为下标的结构
            $photoList = array_column($photoList, null, 'id');
        }

        /*  */
        $data = [];
        foreach ($order['data'] as $key => $value) {
            $data[$key]['id'] = $value['id'];
            $data[$key]['order_no'] = $value['order_no'];
            $data[$key]['order_num'] = $value['order_num'];
            $data[$key]['order_amount'] = $value['total_amount'];
            $data[$key]['payment_method'] = $value['payment_method'];
            $data[$key]['pay_terms'] = $value['pay_terms'];
            $data[$key]['status'] = $value['status'];
            $data[$key]['status_text'] = $WholesalOrderModel->getStatusText($value['status']);

            $data[$key]['create_time'] = $value['create_time'];
            $data[$key]['order_remark'] = $value['order_remark'];

            $order_item = [];
            if (!empty($value['item'])) {
                foreach ($value['item'] as $k => $item) {

                    $k = implode('_', [
                        $item['product_id'],
                        $item['warehouse_id'],
                        $item['arrival_date'],
                        $item['is_futures']
                    ]);

                    /* 合并 */
                    if (isset($order_item[$k])) {
                        $order_item[$k]['quantity'] = Calculate::pricecalc($order_item[$k]['quantity'], '+', $item['quantity'], 0);
                        $order_item[$k]['total_qty'] = Calculate::pricecalc($order_item[$k]['total_qty'], '+', $item['total_qty'], 0);
                        continue;
                    }

                    /* 库存 */
                    $order_item[$k]['item_id'] = $item['id'];
                    $order_item[$k]['product_id'] = $item['product_id'];
                    $order_item[$k]['warehouse_id'] = $item['warehouse_id'];
                    $order_item[$k]['original_price'] = $item['original_price'];
                    $order_item[$k]['actual_price'] = $item['actual_price'];
                    $order_item[$k]['is_futures'] = $item['is_futures'];
                    $order_item[$k]['quantity'] = $item['quantity'];
                    $order_item[$k]['lock_qty'] = $item['lock_qty'];
                    $order_item[$k]['total_qty'] = Calculate::pricecalc($order_item[$k]['quantity'], '+', $item['lock_qty'], 0);

                    /* 产品 */
                    if (!empty($item['product'])) {

                        $order_item[$k]['name'] = $item['product']['cname'];

                        /* 分类 */
                        if (!empty($item['product']['category'])) {
                            $order_item[$k]['category_id'] = $item['product']['category']['id'];
                            $order_item[$k]['category_name'] = $item['product']['category']['name'];
                        }

                        /* 品牌 */
                        if (!empty($item['product']['brand'])) {
                            $order_item[$k]['brand_id'] = $item['product']['brand']['id'];
                            $order_item[$k]['brand_name'] = $item['product']['brand']['name'];
                            $order_item[$k]['brand_icon'] = Config::get('api.cdn') . $item['product']['brand']['image'];
                        }

                        /* 缩略图 */
                        if (!empty($item['product']['photo']) && $item['product']['type'] == 2) {
                            $photoKey = explode(',',$item['product']['photo'])[0];
                            $order_item[$k]['thumb'] =$photoList[$photoKey]['url'] ?? '';
                        }
                        /* 缩略图 */
                        if (!empty($item['product']['main_photo'])) {
                            $order_item[$k]['thumb'] = $photoList[$item['product']['main_photo']]['url'] ?? '';
                        }
                        $order_item[$k]['expiration_date'] = $item['product']['expiration_date'];

                        $order_item[$k]['unit'] = $item['product']['unit'];
                        $order_item[$k]['hashrate'] = $item['product']['hashrate'] . ' ' . $item['product']['unit'];
                        $order_item[$k]['power'] = $item['product']['power'];

                        $order_item[$k]['estimated_ship_date'] = $item['product']['estimated_ship_date'];
                        $order_item[$k]['weight'] = $item['product']['weight'];
                    }
                }
            }

            $data[$key]['item'] = array_values($order_item);
        }
        $order['data'] = $data;
        return Basic::data(0, 'common.success', $order);
    }

    /**
     *  我的资产
     */
    public function assets($param)
    {

        $where['user_id'] = $param['user_id'];
        $where['order_category'] = 'wholesal';
        $result = WholesalOrder::with([
            'item' => function ($query) {
                $query->with([
                    'product' => function ($query) {
                        return $query->with([
                            'brand' => function ($query) {
                                return $query->field('id,name,image');
                            },
                            'category' => function ($query) {
                                return $query->field('id,name');
                            },

                        ])->field('id,cname,category,brand,condition,expiration_date,hashrate,computing_unit,power,main_photo,photo,type,describe,estimated_ship_date,weight');
                    },
                    'warehouse' => function ($query) {
                        return $query->field('id,show_name as name,fl_warehouse_id');
                    }
                ])->where('quantity', '>', 0)
                    ->field('id,order_id,free_shipping,apply_rules,product_id,warehouse_id,original_price,actual_price,quantity,arrival_date,is_futures,lock_qty,pending_quantity');
            }
        ])->where($where)
            ->where('status', '>=', 100)
            ->where('review_node', 0)
            ->field('id,order_no,user_id,order_num,advance_amount,advance_pay_time,payment_method,status,order_remark,tax_package,tax_package_id,tax_fee,pay_terms,total_amount,pay_amount,pay_status,product_total_amount,product_total_original_amount,currency,review_node,billing_email')
            ->select();

        if ($result) {
            $result = $result->toArray();
        } else {
            $data['list'] = [];
            $data['total_count'] = 0;
            return Basic::data(0, 'common.success', $data);
        }

        /**
         *  合并相同服务器数量
         */
        $photoidsArr = [];
        $photoList = [];
        foreach ($result as $datum){
            if($datum['item']){
                foreach ($datum['item'] as $productData){
                    if(!empty($productData['product']['main_photo']) ){
                        $photoidsArr[]=$productData['product']['main_photo'];
                    }
                    if ($productData['product']['type'] == 2 && !empty($productData['product']['photo'])) {
                        $photoidsArr[] = explode(',', $productData['product']['photo'])[0];
                    }
                }
            }
        }

        $imageModel = new Images();
        if($photoidsArr){
            $photoList = $imageModel->getImagesByIds($photoidsArr);

            // 将数组转换为以ID为下标的结构
            $photoList = array_column($photoList, null, 'id');
        }
        $assets = [];
        $common = new \app\api\service\Common();
        foreach ($result as $item) {

            foreach ($item['item'] as $value) {

                $k = implode('_', [
                    $value['product_id'],
                    $value['warehouse_id'],
                    $value['arrival_date'],
                    $value['is_futures']
                ]);

                $value['status'] = $item['status'];
                $value['status_text'] = $item['status_text'];
                $value['pay_status_text'] = $item['pay_status_text'];

                if (isset($assets[$k])) {
                    $assets[$k]['quantity'] = Calculate::pricecalc($assets[$k]['quantity'], '+', $value['quantity'], 0);
                    $assets[$k]['lock_qty'] = Calculate::pricecalc($assets[$k]['lock_qty'], '+', $value['lock_qty'], 0);

                    if (empty($value['pending_quantity'])) {
                        $value['pending_quantity'] = 0;
                    }
                    if (empty($assets[$k]['pending_quantity'])) {
                        $assets[$k]['pending_quantity'] = 0;
                    }
                    $assets[$k]['pending_quantity'] = Calculate::pricecalc($assets[$k]['pending_quantity'], '+', $value['pending_quantity'], 0);

                } else {
                    $assets[$k] = $value;
                }
            }
        }

        $product = [];
        $total_count = 0;
        $key = 0;
        foreach ($assets as $value) {
            $product[$key]['id'] = $value['id'];
            $product[$key]['quantity'] = $value['quantity'];  // 总数量
            $product[$key]['apply_rules'] = $value['apply_rules'];  // 是否用我司物流
            $product[$key]['free_shipping'] = $value['free_shipping'];  // 是否包邮
            $product[$key]['lock_qty'] = $value['lock_qty'];  // 锁定数量
            $product[$key]['pending_quantity'] = Calculate::pricecalc($value['pending_quantity'], '-', $value['lock_qty'], 0);

            $product[$key]['is_futures'] = $value['is_futures'];
            $product[$key]['original_price'] = is_null($value['original_price']) ? '' : $value['original_price'];
            $product[$key]['actual_price'] = is_null($value['actual_price']) ? '' : $value['actual_price'];
            $product[$key]['shipping_qty'] = 0;

            /* 数量 */
            $total_count = Calculate::pricecalc($total_count, '+', $value['quantity'], 0);

            if (!empty($value['product']))
            $product[$key]['product_id'] = $value['product']['id'];
            $product[$key]['name'] = $common->singleTranslate($value['product']['cname'],$param['lang']);
            $product[$key]['condition'] = $value['product']['condition'];
            $product[$key]['expiration_date'] = $value['product']['expiration_date'];
            $product[$key]['unit'] = $value['product']['unit'];
            $product[$key]['hashrate'] = $value['product']['hashrate'] . ' ' . $value['product']['unit'];
            $product[$key]['power'] = $value['product']['power'];
            $product[$key]['describe'] = $value['product']['describe'];
            $product[$key]['estimated_ship_date'] = $value['product']['estimated_ship_date'];
            $product[$key]['weight'] = $value['product']['weight'];


            /* 缩略图 */
            if (!empty($value['product']['photo']) && $value['product']['type'] == 2) {
                $photoKey = explode(',',$value['product']['photo'])[0];
                $product[$key]['thumb'] =$photoList[$photoKey]['url'] ?? '';
            }
            /* 缩略图 */
            if (!empty($value['product']['main_photo'])) {
                $product[$key]['thumb'] = $photoList[$value['product']['main_photo']]['url'] ?? '';
            }
            /* 分类 */
            if (!empty($value['product']['category'])) {
                $product[$key]['category_id'] = $value['product']['category']['id'];
                $product[$key]['category_name'] = $value['product']['category']['name'];
            }

            /* 品牌 */
            if (!empty($value['product']['brand'])) {
                $product[$key]['brand_id'] = $value['product']['brand']['id'];
                $product[$key]['brand_name'] = $common->singleTranslate($value['product']['brand']['name'],$param['lang']);
                $product[$key]['brand_icon'] = $value['product']['brand']['brand_icon'];
            }

            /* 仓库 */
            if (!empty($value['warehouse'])) {
                $product[$key]['warehouse_id'] = $value['warehouse']['id'];
                $product[$key]['warehouse_name'] =$common->singleTranslate($value['warehouse']['name'],$param['lang']);
                $product[$key]['fl_warehouse_id'] = $value['warehouse']['fl_warehouse_id'];
            }

            /* 订单信息 */
            if (!empty($value['orderInfo'])) {
                $product[$key]['status_text'] = $value['orderInfo']['status_text'];
                $product[$key]['pay_status_text'] = $value['orderInfo']['pay_status_text'];
                $product[$key]['pay_terms_text'] = $value['orderInfo']['pay_terms_text'];
                $product[$key]['status'] = $value['orderInfo']['status'];
                $product[$key]['pay_status'] = $value['orderInfo']['pay_status'];
            }
            $key++;
        };

        $data['list'] = $product;
        $data['total_count'] = $total_count;
        return Basic::data(0, 'common.success', $data);
    }

    /**
     *  下单结算页面
     */
    public function checkout($param)
    {
        /* ids */
        $ids = [];
        $ids_arr = [];
        foreach ($param['ids'] as $v) {
            $ids_arr[$v['id']] = $v['quantity'];
            $ids[] = $v['id'];
        }
        $common = new \app\api\service\Common();
        $where['user_id'] = $param['user_id'];

        $result = WholesalOrderItem::with(['product' => function ($query) {
            return $query->with([
                'brand' => function ($query) {
                    return $query->field('id,name,image');
                },
                'category' => function ($query) {
                    return $query->field('id,name');
                },

            ])->field('id,cname,category,brand,condition,expiration_date,hashrate,computing_unit,power,main_photo,photo,type,describe,estimated_ship_date,weight');
        }, 'warehouse' => function ($query) {
            $query->field('id,show_name as name');
        }])->where($where)
            ->field('id,user_id, product_id, warehouse_id,arrival_date,is_futures')
            ->where('id', 'in', $ids)
            ->select();

        if ($result) {
            $result = $result->toArray();

        } else {
            $result = [];
        }
        $photoidsArr = [];
        $photoList = [];

        foreach ($result as $productData) {
            if (!empty($productData['product']['main_photo'])) {
                $photoidsArr[] = $productData['product']['main_photo'];
            }
            if ($productData['product']['type'] == 2 && !empty($productData['product']['photo'])) {
                $photoidsArr[] = explode(',', $productData['product']['photo'])[0];
            }
        }

        $imageModel = new Images();
        if($photoidsArr){
            $photoList = $imageModel->getImagesByIds($photoidsArr);

            // 将数组转换为以ID为下标的结构
            $photoList = array_column($photoList, null, 'id');
        }

        $product = [];

        foreach ($result as $key => $value) {


            $product[$key]['quantity'] = $ids_arr[$value['id']];
            if (!empty($value['product'])) {
                $product[$key]['name'] =$common->singleTranslate($value['product']['cname'],$param['lang']) ;
            }

            $product[$key]['condition'] = $value['product']['condition'];
            $product[$key]['expiration_date'] = $value['product']['expiration_date'];
            $product[$key]['unit'] = $value['product']['unit'];
            $product[$key]['hashrate'] = $value['product']['hashrate'] . ' ' . $value['product']['unit'];
            $product[$key]['power'] = $value['product']['power'];
            $product[$key]['describe'] = $value['product']['describe'];
            $product[$key]['estimated_ship_date'] = $value['product']['estimated_ship_date'];
            $product[$key]['weight'] = $value['product']['weight'];


            /* 缩略图 */
            if (!empty($value['product']['photo']) && $value['product']['type'] == 2) {
                $photoKey = explode(',',$value['product']['photo'])[0];
                $product[$key]['thumb'] =$photoList[$photoKey]['url'] ?? '';
            }
            /* 缩略图 */
            if (!empty($value['product']['main_photo'])) {
                $product[$key]['thumb'] = $photoList[$value['product']['main_photo']]['url'] ?? '';
            }

            /* 分类 */
            if (!empty($value['product']['category'])) {
                $product[$key]['category_id'] = $value['product']['category']['id'];
                $product[$key]['category_name'] = $value['product']['category']['name'];
            }

            /* 品牌 */
            if (!empty($value['product']['brand'])) {
                $product[$key]['brand_id'] = $value['product']['brand']['id'];
                $product[$key]['brand_name'] = $common->singleTranslate($value['product']['brand']['name'],$param['lang']) ;
                $product[$key]['brand_icon'] = $value['product']['brand']['brand_icon'];
            }

            /* 仓库 */
            if (!empty($value['warehouse'])) {
                $product[$key]['warehouse_id'] = $value['warehouse']['id'];
                $product[$key]['warehouse_name'] = $common->singleTranslate($value['warehouse']['name'],$param['lang']);
            }
        }

        /* 获取用户Emdil */
        $email = Customer::where('id', $param['user_id'])->value('email');
        if ($email) {
            $data['billing_email'] = $email;
        } else {
            $data['billing_email'] = '';
        }

        $data['product'] = $product;

        /* 我的收货地址 */
        $data['address_id'] = null;

        /* 自提地址 */
        $warehouse = $this->getwarehouseAddress($ids);

        if ($warehouse['code'] == 0) {
            $data['pickup_address'] = $warehouse['data'];
        } else {
            $data['pickup_address'] = '';
        }

        /* tax Package */
        $TaxPackage = new TaxPackage();
        $data['tax_package'] = $TaxPackage->getTaxPackageList();
        $data['tax_package_id'] = $data['tax_package'][0]['id'];

        /* 是否采购订单 */
        $data['is_wholesal'] = 0;

        $ModelOrder = new ModelOrder();

        /* 物流方式 */
        $data['delivery_method'] = $ModelOrder->getAttributes('delivery_method');
        foreach ($data['delivery_method'] as &$delivery){
            $delivery['label'] = $common->singleTranslate($delivery['label'],$param['lang']);
        }
        $data['delivery_method_id'] = 1;

        /* 物流时效 */
        $data['prescription_method'] = $ModelOrder->getAttributes('prescription');
        $data['prescription'] = 1;

        /* 贸易条款 */
        $data['delivery_terms_method'] = $ModelOrder->getAttributes('delivery_terms');
        $data['delivery_terms'] = 1;

        /* 付款方式 */
        $data['pay_terms_method'] = $ModelOrder->getAttributes('pay_terms');
        $data['pay_terms'] = 0;

        /* 是否采购订单 */
        $data['is_wholesal'] = 0;

        /* 获取用户Emdil */
        $email = Customer::where('id', $param['user_id'])->value('email');
        if ($email) {
            $data['billing_email'] = $email;
        } else {
            $data['billing_email'] = '';
        }


        /* 支付方式 */
        $PaymentMethod = new PaymentMethod();
        $data['payment_method'] = $PaymentMethod->getPaymentMethodList($param);
        $data['payment_method_id'] = $data['payment_method'][0]['id'];
        foreach ($data['payment_method'] as &$payment_method_list)
        {
            $payment_method_list['name'] = $common->singleTranslate($payment_method_list['name'],$param['lang']);
        }

        /* 转转支付信息 */
        $data['payment_information'] = $PaymentMethod->getPaymentInformation();

        /* 物流费用 */
        $data['shipping_amount'] = 0.00;

        return Basic::data(0, 'common.success', $data);
    }

    /**
     *  进销商发货
     */
    public function create($param)
    {
        $ids = [];
        $iterm = [];
        $productFee = [];
        $data = [];
        $data['order_num'] = 0;
        foreach ($param['ids'] as $val) {
            $iterm[] = $val['id'];
            $data['order_num']+=$val['quantity'];
            $ids[$val['id']] = $val['quantity'];
            $val['id'] = $val['product_id'];
            $productFee[] = $val;
        }

       $source = $this->getOrderMessageForOrderNo($iterm);
        /* 获取订单 */
        $common = new Common();
        $data['order_no'] = $common->generateOrderNoZc($param['owner'] ?? 0);
        $data['create_time'] = date("Y-m-d H:i:s", time());
        $data['user_id'] = $param['user_id'];
        $data['order_type'] = 2;
        /* 订单 */
        $data['status'] = 10;
        /* 使用快递 */
        if ($param['delivery_method'] == 1) {

            /* 查询收货地址 */
            $address = AddressModel::where([
                'user_id' => $param['user_id'],
                'type' => 1,
                'id' => $param['address_id'],
            ])->field('id,first_name,last_name,email,phone,address,country_id,country_name,city_id,city_name,zip_code,state,company,address2')
                ->find();

            if (!$address) {
                return Basic::data(1, 'order.deliveryAddressError');
            }
            $data['address_id'] = $address->id;
            $data['first_name'] = $address->first_name;
            $data['last_name'] = $address->last_name;
            $data['email'] = $address->email;
            $data['phone'] = $address->phone;
            $data['address'] = $address->address;
            $data['country_id'] = $address->country_id;
            $data['country_name'] = $address->country_name;
            $data['city_id'] = $address->city_id;
            $data['city_name'] = $address->city_name;
            $data['zip_code'] = $address->zip_code;
            $data['state'] = $address->state;
            $data['company'] = $address->company;
            $data['address2'] = $address->address2;
        }

        /* 用户选择自提地址 */
        if ($param['delivery_method'] == 0) {
            $data['pickup_name'] = $param['pickup_name'];
            $data['pickup_phone'] = $param['pickup_phone'];
            $data['pickup_passport'] = $param['pickup_passport'];
            $data['pickup_vehicle'] = $param['pickup_vehicle'];
            $data['warehouse_code'] = $param['warehouse_code'];
            /* 订单 */
            $data['status'] = 30;
            /* 生产自提码 */
            $data['pickup_code'] = generateUniqueString();

            /* 自提地址 */
            $ids = array_column($param['ids'], 'id');
            $warehouse = $this->getwarehouseAddress($ids);
            if ($warehouse['code'] == 0) {
                $data['pickup_address'] = $warehouse['data'];
            } else {
                return Basic::data(1, $warehouse['message']);
            }
        }

        if ($param['delivery_method'] == 2) {
            $data['pickup_name'] = $param['pickup_name'];
            $data['pickup_phone'] = $param['pickup_phone'];
            $data['pickup_passport'] = $param['pickup_passport'];

            $data['warehouse_code'] = $param['warehouse_code'];
            /* 订单 */
            $data['status'] = 30;
        }

        /*  */
        $data['delivery_method'] = $param['delivery_method']; // 收货方式(0-自提 1-快递)
        $data['delivery_terms'] = $param['delivery_terms'];   // 贸易条款(1-DDP 2-DDU)
        $data['prescription'] = $param['prescription'];     // 1普快/2特快
        /* 查询收货地址 */
        if(isset($param['billing_address_id']) && $param['billing_address_id']){
            $billing_address = AddressModel::where([
                'user_id' => $param['user_id'],
                'type' => 2,
                'id' => $param['billing_address_id'],
            ])
                ->field('id,first_name,last_name,email,phone,address,country_id,country_name,city_id,city_name,zip_code,state,company,address2')
                ->find();
            $data['billing_address_id'] = $billing_address->id;
            $data['billing_first_name'] = $billing_address->first_name;
            $data['billing_last_name'] = $billing_address->last_name;
            $data['billing_email'] = $billing_address->email;
            $data['billing_phone'] = $billing_address->phone;
            $data['billing_address'] = $billing_address->address;
            $data['billing_country_id'] = $billing_address->country_id;
            $data['billing_country_name'] = $billing_address->country_name;
            $data['billing_city_id'] = $billing_address->city_id;
            $data['billing_city_name'] = $billing_address->city_name;
            $data['billing_zip_code'] = $billing_address->zip_code;
            $data['billing_state'] = $billing_address->state;
            $data['billing_company'] = $billing_address->company;
            $data['billing_address2'] = $billing_address->address2;
        }

        /* 支付方式 */
        if (isset($param['payment_method'])) {
            $PaymentMethod = new PaymentMethod();
            $paymentMethodItem = $PaymentMethod->getPaymentMethodItem($param['payment_method']);
            $data['payment_method'] = $paymentMethodItem['id'];
            $data['pay_method_name'] = $paymentMethodItem['name'];
        } else {
            $data['payment_method'] = '';
            $data['pay_method_name'] = '';
        }

        /* 获取运费 */
        if ($param['delivery_method'] == 1) {
            $ccNameId = $address->country_id;
            $to_param = [];
            $to_param['to_nation'] = $ccNameId;
            $to_param['prescription'] = $param['prescription'];
            $to_param['terms'] = $param['delivery_terms'];
            $to_param['product_list'] = [];
            $fee_ids = array_column($productFee, 'id');
            $productInfo = ProductModel::where('id', 'in', $fee_ids)->field('id,billing_weight,free_shipping,apply_rules')->select()->toArray();
            $productInfo = array_column($productInfo, null, 'id');
            foreach ($productFee as &$p) {
                $p['billing_weight'] = $productInfo[$p['id']]['billing_weight'] ?? '';
                $p['free_shipping'] = $productInfo[$p['id']]['free_shipping'] == 0 ? false : true;
                $p['apply_rules'] = $productInfo[$p['id']]['apply_rules'] == 0 ? false : true;
                $p['num'] = $p['quantity'];
            }
            $to_param['product_list'] = $productFee;
            $fee = (new LogisticsRules())->getLogisticsFee($to_param);
            if (!isset($fee['data']['logistics_fee'])) {
                $data['logistics_fee'] = 0.00;
            } else {
                $data['logistics_fee'] = $fee['data']['logistics_fee'];
            }
            /* 运费为0 订单需要审核 */
            if ($data['logistics_fee'] == 0) {
                $data['status'] = 20;
                $data['review_node'] = 5;
            }

        } else {
            $data['logistics_fee'] = 0.00;
        }

        /* 全款 */
        $data['pay_terms'] = 0;

        /* 支付价格 */
        $data['pay_amount'] = 0.00;

        /* 支付状态 */
        $data['pay_status'] = 1;

        /* 订单运费 */
        $data['source'] = 1;

        /* 订单总结金额 */
        $data['total_amount'] = $data['logistics_fee'];

        /* 采购单商品 */
        $product = $this->getOrderProductList($param);

        /* 总价 */
        $data['product_total_amount'] = $product['product_total_amount'];
        /* 商品实际购买价格合计 */
        $data['product_total_original_amount'] = $product['product_total_original_amount'];

        Db::startTrans();

        try {

            $result = ModelOrder::create($data);
            /* 锁定数量 */
            $itmeList = [];
            $lockStock = [];
            foreach ($product['list'] as $key => $value) {

                $itmeList[$key]['user_id'] = $result->user_id;
                $itmeList[$key]['order_id'] = $result->id;
                $itmeList[$key]['product_id'] = $value['product_id'];
                $itmeList[$key]['warehouse_id'] = $value['warehouse_id'];
                $itmeList[$key]['original_price'] = $value['original_price'];
                $itmeList[$key]['actual_price'] = $value['actual_price'];
                $itmeList[$key]['is_futures'] = $value['is_futures'];
                $itmeList[$key]['create_time'] = date('Y-m-d H:i:s', time());
                $itmeList[$key]['wholesal_id'] = $value['order_id'];
                $itmeList[$key]['quantity'] = $value['pay_quantity'];
                $itmeList[$key]['pending_quantity'] = $value['pay_quantity'];
                $itmeList[$key]['arrival_date'] = $value['arrival_date'];
                $itmeList[$key]['is_futures'] = $value['is_futures'];
                $itmeList[$key]['is_advance'] = $value['is_advance'];
                $itmeList[$key]['advance_ratio'] = $value['advance_ratio'];
                $lockStock[$key]['id'] = $value['id'];
                $lockStock[$key]['quantity'] = $value['pay_quantity'];

                /* 新增 */
                $itmeList[$key]['transaction_currency_id'] = $value['transaction_currency_id'];
                $itmeList[$key]['price_selected_currency'] = $value['price_selected_currency'];
                $itmeList[$key]['purchase_currency'] = $value['purchase_currency'];
                $itmeList[$key]['purchase_price'] = $value['purchase_price'];

            }

            /* 写入明细 */
            if (!OrderItem::insertAll($itmeList)) {
                throw new ThrowException([
                    'message' => '普通订单明细表创建失败'
                ]);
            }

            /* 锁定 */
            $this->lockStock($lockStock);

            /* 发送定时任务 */
//            $inventory = new Inventory();
//            $inventory->wholesalOrderTask($result);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return Basic::data(1, 'order.createOrderError');
        }

        /* 支付 */
        $OrderPayment = new OrderPayment();
        return $OrderPayment->goPay($result, $param);
    }
    private function getOrderMessageForOrderNo($ids)
    {
        $source = 1;
        $order = Db::name('order_item')
            ->alias('item')
            ->join('db_order o', 'item.order_id = o.id')
            ->where('item.id', 'in', $ids)
             ->field('o.*')->group('item.order_id')->select()->toArray();
        if($order){
            foreach ($order as $o){
                if($source == 2){
                    continue;
                }
                if($o['owner'] || $o['contract_type'] == 2 || stripos($o['order_no'],'HK') !== false){
                    $source =2;
                }
            }
        }
        return $source;
    }

    /**
     *  获取订单商品
     */
    public function getOrderProductList($param)
    {
        /* ids */
        $ids = [];
        $ids_arr = [];
        foreach ($param['ids'] as $v) {
            $ids_arr[$v['id']] = $v['quantity'];
            $ids[] = $v['id'];
        }

        $data = [];
        $result = WholesalOrderItem::where('id', 'in', $ids)
            ->field('id,order_id,product_id,warehouse_id,original_price,actual_price,pending_quantity,arrival_date,is_futures,lock_qty')
            ->select();

        if (!$result) {
            return Basic::data(0, 'order.shoppingCartNotExist');
        }


        $result = $result->toArray();


        /* 购买商品的所有 */
        $wholesalOrderItemAll = [];
        foreach ($result as $key => $value) {
//            $order_Item_where['user_id'] = $param['user_id'];
//            $order_Item_where['product_id'] = $value['product_id'];
//            $order_Item_where['warehouse_id'] = $value['warehouse_id'];
//            $order_Item_where['arrival_date'] = $value['arrival_date'];
//            $order_Item_where['is_futures'] = $value['is_futures'];
//
//
//
//            $wholesalOrderItem = WholesalOrderItem::with(['orderInfo'=>function ($query){
//                    return $query->where(['review_node' => 0,'order_category'=>'wholesal']);
//            } ])->where($order_Item_where)->where('pending_quantity', '>', 0)->order('id', 'ASC')->select()->toArray();
//


            // 获取子订单详情
            $whereItem = [
                ['item.product_id', '=', $value['product_id']],
                ['item.is_futures', '=', $value['is_futures']],
                ['item.warehouse_id', '=', $value['warehouse_id']],
                ['item.arrival_date', '=', $value['arrival_date']],
                ['item.user_id', '=', $param['user_id']]
            ];
            $wholesalOrderItem = Db::name('order_item')
                ->alias('item')
                ->join('db_order o', 'item.order_id = o.id')
                ->where('o.order_category', '=', 'wholesal')
                ->where('o.review_node', '=', 0)
                ->where('o.status', '=', 100)
                ->where($whereItem)->order('item.id', 'asc')->field('item.*')->select()->toArray();

            /* 购买数量 */
            $buy_quantity = $ids_arr[$value['id']];
            $total_quantity = 0;
            foreach ($wholesalOrderItem as $v => $item) {

                if ($buy_quantity == 0) {
                    break;
                }

                /* 当前数量 */
                $current_quantity = Calculate::pricecalc($item['pending_quantity'], '-', $item['lock_qty'], 0);
                $total_quantity = Calculate::pricecalc($total_quantity, '+', $current_quantity, 0);
                if ($current_quantity == 0) {
                    continue;
                }

                if ($buy_quantity >= $current_quantity) {
                    $buy_quantity = Calculate::pricecalc($buy_quantity, '-', $current_quantity, 0);
                    $item['pay_quantity'] = $current_quantity;
                    $wholesalOrderItemAll[] = $item;
                } else {
                    $item['pay_quantity'] = $buy_quantity;
                    //$buy_quantity = Calculate::pricecalc($current_quantity,'-',$buy_quantity,0);
                    $wholesalOrderItemAll[] = $item;
                    break;
                }
            }

            /* 库存不足 */
            if ($total_quantity < $ids_arr[$value['id']]) {
                return Basic::data(0, 'order.shoppingCartNotEnough');
            }
        }

        $product_total_amount = 0;
        $product_total_original_amount = 0;
        foreach ($wholesalOrderItemAll as $key => $value) {
            $actual_price = Calculate::pricecalc($value['pay_quantity'], '*', $value['actual_price'], 2);
            $product_total_amount = Calculate::pricecalc($product_total_amount, '+', $actual_price, 2);
            $original_price = Calculate::pricecalc($value['pay_quantity'], '*', $value['original_price'], 2);
            $product_total_original_amount = Calculate::pricecalc($product_total_original_amount, '+', $original_price, 2);
        }

        $res_data = [];
        $res_data['product_total_amount'] = $product_total_amount;
        $res_data['product_total_original_amount'] = $product_total_original_amount;
        $res_data['list'] = $wholesalOrderItemAll;

        return $res_data;
    }


    /**
     *  获取订单详情
     */
    public function orderDetail($param)
    {

        $where['user_id'] = $param['user_id'];
        $where['order_no'] = $param['order_no'];
        $common = new \app\api\service\Common();
        $result = WholesalOrder::with([
            'item' => function ($query) {
                $query->with([
                    'product' => function ($query) {
                        return $query->with([
                            'brand' => function ($query) {
                                return $query->field('id,name,image');
                            },
                            'category' => function ($query) {
                                return $query->field('id,name');
                            },

                        ])->field('id,cname,category,brand,condition,expiration_date,hashrate,computing_unit,power,main_photo,photo,type,describe,estimated_ship_date,weight');
                    },
                ])->where('is_del', '=', 0)->field('id,order_id,product_id,warehouse_id,original_price,actual_price,is_futures,quantity,arrival_date,lock_qty');
            },
            'payment_record' => function ($query) {
                $query->with([
                    'images' => function ($query) {
                        $query->field('id,url');
                    }
                ])->where('order_type', 'wholesal')
                    ->field('id,order_id,payment_method,payment_method_name,pay_type,pay_time,pay_amount,pay_code,create_time,reviewer,reviewer_time,transfer_voucher_id,status,notes,order_no,user_id');
            }
        ])->where($where)
            ->find();

        if (!$result) {
            return Basic::data(0, 'order.orderNotExist');
        }

        $result = $result->toArray();
        $photoidsArr = [];
        $photoList = [];
        if($result['item']){
            foreach ($result['item'] as $productData ){
                if(!empty($productData['product']['main_photo']) ){
                    $photoidsArr[]=$productData['product']['main_photo'];
                }
                if ($productData['product']['type'] == 2 && !empty($productData['product']['photo'])) {
                    $photoidsArr[] = explode(',', $productData['product']['photo'])[0];
                }
            }
            $imageModel = new Images();
            if($photoidsArr){
                $photoList = $imageModel->getImagesByIds($photoidsArr);

                // 将数组转换为以ID为下标的结构
                $photoList = array_column($photoList, null, 'id');
            }

        }

        /* 商品明细 */
        $item_list = [];
        foreach ($result['item'] as $key => $item) {

            $key = implode('_', [
                $item['product_id'],
                $item['warehouse_id'],
                $item['arrival_date'],
                $item['is_futures']
            ]);

            /* 合并 */
            if (isset($item_list[$key])) {
                $item_list[$key]['lock_qty'] = Calculate::pricecalc($item_list[$key]['lock_qty'], '+', $item['lock_qty'], 0);
                $item_list[$key]['quantity'] = Calculate::pricecalc($item_list[$key]['quantity'], '+', $item['quantity'], 0);
                $item_list[$key]['total_qty'] = Calculate::pricecalc($item_list[$key]['quantity'], '+', $item_list[$key]['lock_qty'], 0);
                continue;
            }

            $item_list[$key]['id'] = $item['id'];
            $item_list[$key]['original_price'] = $item['original_price'];
            $item_list[$key]['actual_price'] = $item['actual_price'];
            $item_list[$key]['is_futures'] = $item['is_futures'];
            $item_list[$key]['product_id'] = $item['product_id'];

            /* 数量 */
            $item_list[$key]['lock_qty'] = $item['lock_qty'];
            $item_list[$key]['quantity'] = $item['quantity'];
            $item_list[$key]['total_qty'] = Calculate::pricecalc($item['lock_qty'], '+', $item['quantity'], 0);

            /* 商品详情 */
            if (!empty($item['product'])) {

                $item_list[$key]['name'] =  $common->singleTranslate($item['product']['cname'],$param['lang']);

                /* 缩略图 */
                if (isset($item['product']['main_photo'])) {
                    $item_list[$key]['thumb'] = $photoList[$item['product']['main_photo']]['url'];
                } elseif($item['product']['type'] == 2 && isset($item['product']['photo']) && $item['product']['photo']) {

                    $photoKey = explode(',',$item['product']['photo'])[0];
                    $item_list[$key]['thumb'] =$photoList[$photoKey]['url'];
                }

                /* 分类 */
                if (!empty($item['product']['category'])) {
                    $item_list[$key]['category_id'] = $item['product']['category']['id'];
                    $item_list[$key]['category_name'] = $item['product']['category']['name'];
                }

                /*  brand */
                if (!empty($item['product']['brand'])) {
                    $item_list[$key]['brand_id'] = $item['product']['brand']['id'];
                    $item_list[$key]['brand_name'] = $common->singleTranslate($item['product']['brand']['name'],$param['lang']);
                    $item_list[$key]['brand_icon'] = $item['product']['brand']['brand_icon'];
                }

                $item_list[$key]['condition'] = $item['product']['condition'];
                $item_list[$key]['expiration_date'] = $item['product']['expiration_date'];
                $item_list[$key]['unit'] = $item['product']['unit'];
                $item_list[$key]['hashrate'] = $item['product']['hashrate'] . ' ' . $item['product']['unit'];
                $item_list[$key]['power'] = $item['product']['power'];
                $item_list[$key]['estimated_ship_date'] = $item['product']['estimated_ship_date'];
                $item_list[$key]['weight'] = $item['product']['weight'];
            }
        }

        /* 转账显示银行信息 */
        $PaymentMethod = new PaymentMethod();
        $result['payment_information'] = $PaymentMethod->getPaymentInformation();

        /* 支付方式 */
        $PaymentMethod = new PaymentMethod();
        $result['payment_method_list'] = $PaymentMethod->getPaymentMethodList($param);
        foreach ($result['payment_method_list'] as &$payment_method_list)
        {
            $payment_method_list['name'] = $common->singleTranslate($payment_method_list['name'],$param['lang']);
        }
        /* 支付凭证 */
        $voucher = [];
        if (isset($result['payment_record'])) {
            foreach ($result['payment_record'] as $k => $voucherItem) {

                if (isset($voucherItem['images'])) {
                    $voucherItem['payment_voucher_url'] = $voucherItem['images']['url'];
                    unset($voucherItem['images']);
                }
                $voucher[$k] = $voucherItem;
            }
        }
        if($result['status_text']){
            $result['status_text'] = $common->singleTranslate($result['status_text'],$param['lang']);
        }
        if($result['pay_method_name']){
            $result['pay_method_name'] = $common->singleTranslate($result['pay_method_name'],$param['lang']);
        }
        $result['payment_record'] = $voucher;
        unset($result['item']);
        $result['list'] = array_values($item_list);
        return Basic::data(0, 'common.success', $result);
    }


    /**
     *  订单商品名称
     */
    public function getProductInfo($order)
    {
        $result = WholesalOrderItem::with(['product' => function ($query) {
            $query->field('id,cname');
        }])->field('id,order_id,product_id,quantity')->where('order_id', $order->id)->select();

        if (!$result) {

            $data['name'] = '';
            $data['description'] = '';
            return $data;
        }

        $result = $result->toArray();

        $count = 0;
        $description = '';
        foreach ($result as $key => $item) {
            $count = Calculate::pricecalc($count, '+', $item['quantity'], 0);
            if ($key == 0) {
                $data['name'] = $item['product']['cname'];
            }
            $str = 'Waiting for (' . $count . ') products';
            $description .= $item['product']['cname'] . '(' . $item['quantity'] . '),';
        }

        $data['name'] = $data['name'] . $str;
        $data['description'] = substr($description, 0, -1);

        return $data;

    }


    /**
     *  删除支付凭证
     */
    public function VoucherRemove($param)
    {

        $where['user_id'] = $param['user_id'];
        $where['id'] = $param['id'];

        $PaymentVoucher = ModelOrderPayment::where($where)->find();

        if (empty($PaymentVoucher)) {
            return Basic::data(1, 'order.voucherNotExist');
        }

        if ($PaymentVoucher->payment_method !== '3') {
            return Basic::data(1, 'order.voucherMethodError');
        }

        if ($PaymentVoucher->status !== '00') {
            return Basic::data(1, 'order.voucherStatusError');
        }

        $result = $PaymentVoucher->delete();
        if ($result) {
            return Basic::data(0, 'common.success');
        } else {
            return Basic::data(1, 'common.error');
        }
    }

    /**
     *  获取订单状态列表
     */
    public function getStatusList($lang)
    {
        $WholesalOrderModel = new WholesalOrder();
        $StatusList = $WholesalOrderModel->getFieldEnum('all');
        $common = new \app\api\service\Common();
        $Status[] = [
            'name' => Lang::get('status.all'),
            'value' => 'all'
        ];

        foreach ($StatusList['status'] as $key => $value) {
            if (array_search($key, ['all', 10, 20, 30, 40, 70, 100], true)) {
                # 翻译
                $Status[] = [
                    'name' => $value,
                    'value' => strval($key)
                ];
            }
        }
        foreach ($Status as &$status) {
            $status['name'] = $common->singleTranslate($status['name'],$lang);
        }

        return Basic::data(0, 'common.success', $Status);
    }


    /**
     *  拉起支付
     */
    public function payment($param)
    {
        $where['user_id'] = $param['user_id'];
        $where['order_no'] = $param['orderNo'];
        $where['is_del'] = 0;

        $order = WholesalOrder::where($where)->find();

        if (empty($order)) {
            return Basic::data(1, 'order.orderNotExist');
        }

        /* 支付状态 */
        if ($order->pay_status == 3) {
            return Basic::data(1, 'order.orderPayStatusError');
        }

        $OrderPayment = new ServiceOrderPayment();

        if ($param['payment_method'] < 3) {
            $order_payment = ModelOrderPayment::where([
                'order_id' => $order->id,
                'payment_method' => $param['payment_method'],
            ])->where('status', 'in', ['00', '01', '02'])
                ->where('order_type', 'wholesal')
                ->find();

            if ($order_payment) {
                /* 继续支付 */
                return Basic::data(0, 'common.success', [
                    'order_type' => $order_payment->order_type,
                    'order_no' => $order_payment->order_no,
                    'payment_url' => $order_payment->payment_url
                ]);

            } else {
                /* 支付 */
                return $OrderPayment->goPay($order, $param);
            }

        } elseif ($param['payment_method'] == 3) {
            /* 上传凭证 */
            return $OrderPayment->goPay($order, $param);
        } else {
            return Basic::data(1, 'order.orderPaymentMethodError');
        }
    }

    /**
     *  锁定库存
     */
    public function lockStock($data)
    {
        foreach ($data as $value) {
            $reslut = WholesalOrderItem::where('id', $value['id'])
                ->whereRaw(' pending_quantity - lock_qty >= ? ',[$value['quantity']])
                ->inc('lock_qty', $value['quantity'])
                ->update();
            if (!$reslut) {
                throw new \Exception('扣除进销商库存失败');
            }
        }
    }


    /**
     *  获取仓库地址
     */
    public function getwarehouseAddress($param)
    {
        $warehouse_id = [];

        $result = WholesalOrderItem::where('id', 'in', $param)->field('warehouse_id')->select()->toArray();

        foreach ($result as $value) {
            $warehouse_id[$value['warehouse_id']] = $value['warehouse_id'];
        }

        if (count($warehouse_id) > 1) {
            return Basic::data(1, 'order.multipleWarehousesUnable');
        }

        $warehouse_id = array_shift($warehouse_id);
        $Warehouse = Warehouse::where('id', $warehouse_id)->field('pickup_address')->find();

        $pickup_address = $Warehouse->pickup_address;
        if (empty($pickup_address)) {
            $pickup_address = ' ';
        }
        return Basic::data(0, 'ok', $pickup_address);
    }
}
